import java.util.*;

public class Solution726 {
    public String countOfAtoms(String formula) {
        char[] chars=formula.toCharArray();
        Stack<Map<String,Integer>> stack=new Stack<>();
        Map<String,Integer> map=new HashMap<>();
        int current=0;
        while (current<chars.length){
            if (chars[current]>='A' && chars[current]<='Z') {
                StringBuilder element=new StringBuilder();
                element.append(chars[current]);
                if (current+1<chars.length && chars[current+1]>='a' && chars[current+1]<='z'){
                    element.append(chars[current+1]);
                    current++;
                }
                current++;
                String name=element.toString();
                int num=0;
                if (current<chars.length && chars[current]>='1' && chars[current]<='9'){
                    while (current<chars.length && chars[current]>='0' && chars[current]<='9'){
                        num*=10;
                        num=num+chars[current]-'0';
                        current++;
                    }
                }else{
                    num=1;
                }
                map.put(name,map.getOrDefault(name,0)+num);
                continue;
            }
            if (chars[current]=='('){
                stack.push(map);
                map=new HashMap<>();
                current++;
                continue;
            }
            if (chars[current]==')'){
                current++;
                int num=0;
                if (current<chars.length && chars[current]>='1' && chars[current]<='9'){
                    while (current<chars.length && chars[current]>='0' && chars[current]<='9'){
                        num*=10;
                        num=num+chars[current]-'0';
                        current++;
                    }
                }else{
                    num=1;
                }
                Map<String,Integer> newMap=stack.pop();
                for (Map.Entry<String,Integer> entry:map.entrySet()){
                    newMap.put(entry.getKey(),newMap.getOrDefault(entry.getKey(),0)+entry.getValue()*num);
                }
                map=newMap;
            }
        }
        StringBuilder ans=new StringBuilder();
        List<Map.Entry<String,Integer>> entries=new ArrayList<>(map.entrySet());
        Collections.sort(entries, Comparator.comparing(Map.Entry::getKey));
        for (Map.Entry<String,Integer> entry:entries){
            ans.append(entry.getKey());
            if (entry.getValue()>1){
                ans.append(entry.getValue());
            }
        }
        return ans.toString();
    }

    public static void main(String[] args) {
        System.out.println(new Solution726().countOfAtoms("K4(ON(SO3)2)2"));
    }
}
